package com.stn.zjx.givingtreasure.fragment.bimain;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.address.AddAddressActivity;
import com.stn.zjx.givingtreasure.activity.bi.AddAssetsActivity;
import com.stn.zjx.givingtreasure.activity.bi.BReceivableCodeActivity;
import com.stn.zjx.givingtreasure.activity.bi.BTransferActivity;
import com.stn.zjx.givingtreasure.activity.bi.CreateEthWalletActivity;
import com.stn.zjx.givingtreasure.activity.bi.ImportEthWalletActivity;
import com.stn.zjx.givingtreasure.activity.bi.WalletBackUpActivity;
import com.stn.zjx.givingtreasure.activity.scan.WalletScanActivity;
import com.stn.zjx.givingtreasure.adapter.LeftWalletItemListAdapter;
import com.stn.zjx.givingtreasure.adapter.TokenItemListAdapter;
import com.stn.zjx.givingtreasure.base.BaseBiFragment;
import com.stn.zjx.givingtreasure.domain.TokenListDomain;
import com.stn.zjx.givingtreasure.event.BiMainRefreshEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.RefreshAddAssetsEvent;
import com.stn.zjx.givingtreasure.event.RefreshWalletEvent;
import com.stn.zjx.givingtreasure.event.ScanResultEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.EthNetImpl;
import com.stn.zjx.givingtreasure.service.WalletUserService;
import com.stn.zjx.givingtreasure.table.WalletUser;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.stn.zjx.givingtreasure.widget.MoreLoading;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.view.RxQRCode;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

public class BiAssetsFragment extends BaseBiFragment {


    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.menu_bt)
    RelativeLayout menuBt;
    @BindView(R.id.avatar_civ)
    CircleImageView avatarCiv;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.back_up_tv)
    TextView backUpTv;
    @BindView(R.id.back_up_bt)
    LinearLayout backUpBt;
    @BindView(R.id.go_backup_bt)
    RelativeLayout goBackupBt;
    @BindView(R.id.create_erwei_bt)
    ImageView createErweiBt;
    @BindView(R.id.select_address)
    TextView selectAddress;
    @BindView(R.id.copy_address)
    LinearLayout copyAddress;
    @BindView(R.id.eth_total_tv)
    TextView ethTotalTv;
    @BindView(R.id.money_bt)
    LinearLayout moneyBt;
    @BindView(R.id.add_assets_bt)
    RelativeLayout addAssetsBt;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.scan_bt)
    LinearLayout scanBt;
    @BindView(R.id.create_bt)
    LinearLayout createBt;
    @BindView(R.id.import_bt)
    LinearLayout importBt;
    @BindView(R.id.drawer)
    DrawerLayout drawer;
    @BindView(R.id.avatar_civ_ll)
    LinearLayout avatarCivLl;
    @BindView(R.id.token_rv)
    RecyclerView tokenRv;
    @BindView(R.id.twinkling_refresh)
    TwinklingRefreshLayout twinklingRefresh;


    private LinearLayoutManager left_lm;
    private LeftWalletItemListAdapter walletitemadapter;

    public WalletUser walletUser;
    TokenItemListAdapter tokenItemListAdapter;
    private LinearLayoutManager t_lm;

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public  void ScanResult(ScanResultEvent event){
        switch (event.flag){
            case ScanResultEvent.Wallet_MAIN_Redirect_Transfer:
              Bundle bundle=new Bundle();
                bundle.putString("sendAddress",event.data);
                bundle.putString("address",walletUser.getAddress());
                bundle.putString("tokenAddress","");
                bundle.putString("tokenSymbol","ETH");
                bundle.putInt("tokenDecimal",0);
                RxActivityTool.skipActivity(activity, BTransferActivity.class,bundle);
                break;
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public  void onBiAssets(BiMainRefreshEvent event){
        switch (event.flag){
            case BiMainRefreshEvent.TOTALASSETS:
                   String data=event.data;
                ethTotalTv.setText(String.valueOf(data));
                break;
            case BiMainRefreshEvent.RENAME:
                walletitemadapter.refreshList();
                break;
            case BiMainRefreshEvent.DELETE:
                initRefreshWallet();
                break;

        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public  void onRefreshAddAssetsEvent(RefreshAddAssetsEvent event){
        if(walletUser==null){
            return;
        }
        initRefresh(walletUser.getAddress());
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefresh(RefreshWalletEvent event) {
        if (event == null) {
            return;
        }
        if(event.flag==RefreshWalletEvent.INITREFRESH){
            initRefreshWallet();
            return;
        }
        walletUser = event.walletUser;
        userName.setText(String.valueOf(event.walletUser.getName()));
        if (event.walletUser.getAddress() != null && !event.walletUser.getAddress().equals("")) {
            String ad = event.walletUser.getAddress();
            selectAddress.setText(ad.substring(0, 10) + "..." + ad.substring(ad.length() - 10, ad.length()));
        }
        drawer.closeDrawer(Gravity.RIGHT);
        twinklingRefresh.startRefresh();
    }


    @Override
    public View initView(LayoutInflater inflater, ViewGroup container) {
        if (rootView == null) {
            rootView = View.inflate(activity, R.layout.fragment_bi_main, null);
            ButterKnife.bind(this, rootView);

        }
        return rootView;
    }

    @Override
    public void initData() {
        left_lm = new LinearLayoutManager(activity, OrientationHelper.VERTICAL, false);
        rv.setLayoutManager(left_lm);
        rv.setAdapter(walletitemadapter = new LeftWalletItemListAdapter(activity));

        t_lm = new LinearLayoutManager(activity, OrientationHelper.VERTICAL, false);
        tokenRv.setLayoutManager(t_lm);
        tokenRv.setAdapter(tokenItemListAdapter = new TokenItemListAdapter(this));

        ProgressLayout headerView = new ProgressLayout(activity);
        headerView.setColorSchemeResources(R.color.colorAccent);
        twinklingRefresh.setHeaderView(headerView);
        twinklingRefresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                  if(walletUser==null){
                      twinklingRefresh.finishRefreshing();
                      return;
                  }
                initRefresh(walletUser.getAddress());
            }
        });
        initRefreshWallet();
    }

    public void initRefreshWallet() {
        List<WalletUser> normal_wa = WalletUserService.getInstance(activity).getAllWalletUser(0, 0);
        if (normal_wa != null && normal_wa.size() != 0) {
            walletitemadapter.position = 0;
            walletitemadapter.refreshList(normal_wa);
            RefreshWalletEvent event = new RefreshWalletEvent();
            event.walletUser = walletitemadapter.dataBeanList.get(0);
            EventBus.getDefault()
                    .post(event);
        } else {
            activity.finish();
            walletitemadapter.clearList();
        }

    }


    @OnClick({R.id.back_bt,
            R.id.avatar_civ,
            R.id.avatar_civ_ll,
            R.id.menu_bt,
            R.id.create_erwei_bt,
            R.id.back_up_bt,
            R.id.money_bt,
            R.id.add_assets_bt,
            R.id.scan_bt,
            R.id.create_bt,
            R.id.import_bt,
            R.id.copy_address


    })
    public void onViewClicked(View view) {
        if (walletUser == null) {
            return;
        }
        Bundle bundle=new Bundle();
        switch (view.getId()) {
            case R.id.copy_address:
                if(ToolsUtils.copyKeybroadContent(activity,walletUser.getAddress())){
                    activity.showToast(getString(R.string.already_copy_content));
                }else{
                    activity.showToast(getString(R.string.db_error));
                }
                break;
            case R.id.avatar_civ_ll:
                bundle.putString("address",String.valueOf(walletUser.getAddress()));
                RxActivityTool.skipActivity(activity, WalletBackUpActivity.class,bundle);
                break;
            case R.id.back_bt:
                activity.finish();
                break;
            case R.id.menu_bt:
                drawer.openDrawer(Gravity.RIGHT);
                break;
            case R.id.create_erwei_bt:
//                openDialog(walletUser.getAddress());
                bundle.putString("address",String.valueOf(walletUser.getAddress()));
                RxActivityTool.skipActivity(activity, BReceivableCodeActivity.class,bundle);
                break;
            case R.id.back_up_bt:
                break;
            case R.id.money_bt:
                break;
            case R.id.add_assets_bt:
                bundle.putString("address",String.valueOf(walletUser.getAddress()));
                RxActivityTool.skipActivity(activity, AddAssetsActivity.class,bundle);
                break;
            case R.id.scan_bt:
                bundle.putInt("flag", ScanResultEvent.Wallet_MAIN_Redirect_Transfer);
                RxActivityTool.skipActivity(activity, WalletScanActivity.class,bundle);
                break;
            case R.id.create_bt:
                RxActivityTool.skipActivity(activity, CreateEthWalletActivity.class);
                break;
            case R.id.import_bt:
                RxActivityTool.skipActivity(activity, ImportEthWalletActivity.class);
                break;

        }
    }

    public void openDialog(String address) {
        Dialog dialog = new Dialog(activity);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(R.layout.dialog_show_images);
        ImageView iv = dialog.findViewById(R.id.iv);
        Bitmap bitmap = RxQRCode.creatQRCode(address);
        iv.setImageBitmap(bitmap);
        dialog.show();
    }


    public void initRefresh(String ethAddress) {
        EthNetImpl
                .eth_token_list(ethAddress, ethAddress + "_eth_token_list",
                        new StringCallback() {
                            @Override
                            public void onFinish() {
                                super.onFinish();
                                twinklingRefresh.finishRefreshing();
                            }
                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !activity.isFinishing()) {
                                    TokenListDomain tokenListDomain=new Gson().fromJson(response.body(),TokenListDomain.class);
                                       switch (tokenListDomain.getStatus()){
                                           case BaseApi.REQUEST_SUCCESS_CODE:
                                                  if(tokenListDomain.getData()!=null&&
                                                          tokenListDomain.getData().size()!=0){
                                                      tokenItemListAdapter.refreshList(tokenListDomain.getData());
                                                  }else{
                                                      tokenItemListAdapter.clearList();
                                                  }
                                               break;
                                            default:
                                                tokenItemListAdapter.clearList();
                                                break;
                                       }
                                }
                            }

                            @Override
                            public void onCacheSuccess(Response<String> response) {
                                super.onCacheSuccess(response);
                                if (response.isSuccessful() && !activity.isFinishing()) {
                                    TokenListDomain tokenListDomain=new Gson().fromJson(response.body(),TokenListDomain.class);
                                    switch (tokenListDomain.getStatus()){
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            if(tokenListDomain.getData()!=null&&
                                                    tokenListDomain.getData().size()!=0){
                                                tokenItemListAdapter.refreshList(tokenListDomain.getData());
                                            }else{
                                                tokenItemListAdapter.clearList();
                                            }
                                            break;
                                        default:
                                            tokenItemListAdapter.clearList();
                                            break;
                                    }
                                }
                            }
                        });
    }


}
